<?php

namespace App\Http\Controllers\user;

use Auth;
use Validator;
use Mockery\Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        $result = $this->result();
        try
        {
            $request = $this->getRequest($request);
            $Validator = Validator::make($request, [
                'email' => 'required | email',
                'password' => 'required',
                'is_remember' => 'integer'
            ]);
            //验证失败
            if($Validator->fails())
            {
                //获取错误信息
                $errors = $Validator->errors();
                $result['email']      = $errors->first('email');
                $result['password']   = $errors->first('password');
                $result['is_remember'] = $errors->first('is_remember');
                throw new Exception(config('result.errorRegisterMsg'), config('result.errorRegisterCode'));
            }
            $user['email']    = $request['email'];
            $user['password'] = $request['password'];
            $is_remember = boolval($request['is_remember']);
            if(!Auth::attempt($user, $is_remember))
            {
                throw new Exception(config('result.errorLoginUserOrPasswordMsg'), config('result.errorLoginUserOrPasswordCode'));
            }
        }
        catch (Exception $exception)
        {
            $result['errorCode'] = $exception->getCode();
            $result['errorMsg']  = $exception->getMessage();
        }

        return $result;
    }
}
